﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OverStore;

namespace OverStore.TutorialAsTest.UnitTest
{
    [TestClass]
    public class CacheEnumerableTest
    {
        [TestMethod]
        public void CacheEnumerable()
        {
            var cached = new En().Cache();

            var sum1 = cached.Sum();
            var sum2 = cached.Sum();
            var sum3 = cached.Sum();

            Assert.AreEqual(11, sum1);
            Assert.AreEqual(11, sum2);
            Assert.AreEqual(11, sum3);
        }

        private class En : IEnumerable<int>
        {
            private readonly int[] _Data = new int[] { 1, 2, 3, 5 };

            private int _EnumeratorAccessed;

            public IEnumerator<int> GetEnumerator()
            {
                if (_EnumeratorAccessed > 0)
                    throw new InvalidOperationException("Enumerator requested few times.");
                _EnumeratorAccessed++;
                foreach (var item in _Data)
                {
                    yield return item;
                }
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }
        }
    }
}
